import ArticleItem from "@/components/ArticleItem"
import { InfiniteScroll, PullToRefresh } from "antd-mobile"
import { getArticleList } from "@/store/actions/home"
import { useDispatch, useSelector } from "react-redux"
import styles from "./index.module.scss"
import type { RootState } from "@/types/store"
import { useHistory } from "react-router-dom"
type Props = {
  channelId: number
}
const ArticleList = ({ channelId }: Props) => {
  const dispatch = useDispatch()
  const history = useHistory()
  const { channelArticles } = useSelector((state: RootState) => state.home)
  const currentChannelArticle = channelArticles[channelId] ?? {
    pre_timestamp: Date.now() + "",
    results: [],
  }
  // pre_timestamp 时间戳
  // results 该频道的文章列表数据
  const { pre_timestamp, results } = currentChannelArticle
  async function loadMore() {
    await dispatch(getArticleList(channelId, pre_timestamp, "append"))
  }
  const onRefresh = async () => {
    await dispatch(getArticleList(channelId, Date.now() + "", "replace"))
  }
  const hasMore = pre_timestamp !== null
  const renderArticleList = () => {
    return results.map((item, index) => {
      const {
        title,
        pubdate,
        comm_count,
        aut_name,
        art_id,
        cover: { type, images },
      } = item

      const articleData = {
        art_id,
        title,
        pubdate,
        comm_count,
        aut_name,
        type,
        images,
      }

      return (
        <div
          key={art_id}
          className="article-item"
          onClick={() => history.push(`/article/${art_id}`)}
        >
          <ArticleItem {...articleData} key={art_id} />
        </div>
      )
    })
  }
  return (
    <div className={styles.root}>
      <PullToRefresh onRefresh={onRefresh}>
        {/* 文章列表中的每一项 */}
        {renderArticleList()}

        {/*
        loadMore 加载数据的函数
        hasMore 布尔值，true 表示还有更多数据；false 表示没有更多数据了
      */}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
